/**
 * 电影模块的路由
 */
const Router = require('koa-router');
const router = new Router(); 
const getDb = require('../db');
const  ObjectId  = require('mongodb').ObjectId;


router.all('/consult/add', async (ctx) => {
try {
    let data = {
        ...ctx.params,
        cTime:Date.now(),
        uTime:Date.now()
    }
    let dbo = await getDb();
    await dbo.collection('consult').insertOne(data);
    ctx.body={
        code:1,
        meg:'成功了',
        data
    };
} catch (error) {
    ctx.body={
        code:0,
        meg:error.message
    }
}
});

router.all('/consult/list', async ctx => { 
try {
    let dbo = await getDb();
 let res =   await dbo.collection('consult').find({}).toArray();
    ctx.body = {
       code:1,
       meg:'电影列表',
       res
    }
} catch (error) {
    ctx.body={
        code:0,
        meg:error.message
    }
}
});

router.all('/consult/del', async ctx => {
 if(!ctx.params.id){
    ctx.body={
        code:0,
        msg:'请提供参数'
    }
    return false;
 }
 try {
    let id = ctx.params.id;
    let dbo =await getDb();
 let res=await dbo.collection('consult').deleteOne({
        _id:ObjectId(id)
    });
    if(res.deleteCount > 0){
        ctx.body={
            code:1,
            msg:'删除成功'
        }
    }else{
         ctx.body = {
            code:0,
            msg:'删除失败'
         }   
    }
 } catch (error) {
    ctx.body = {
        code:0,
        msg:error.message
    }
 }
});

router.all('/consult/edit', async ctx => {
try {
    let dbo = await getDb();
    let res = await dbo.collection('consult').updateOne({
        _id: _id
    }, {
        $set: data ={
           data:ctx.params
        }
    })
    ctx.body = {
        code: 1,
        msg: `成功更新${res.modifiedCount}条数据`,
        data: res
    }
} catch (error) {
    ctx.body={
        code:0,
        meg:error.message
    }
}
});


// 把router导出
module.exports = router;